<template>
  <div class="app-container">
    <!-- <div class="filter-container">
      <el-form ref="tableForm" :inline="true" :model="listQuery">
        <el-row>
          <el-col :span="4">
            <el-form-item label="商品标题" prop="nickname">
              <el-input
                v-model="listQuery.nickname"
                style="width: 200px"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="商品ID" prop="mobile">
              <el-input
                v-model="listQuery.mobile"
                style="width: 200px"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="添加时间" prop="created_at">
              <el-date-picker
                v-model="listQuery.created_at"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态" prop="status">
              <el-select v-model="listQuery.status" placeholder="请选择">
                <el-option label="有效" value="1" />
                <el-option label="禁用" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetForm('tableForm')">重置</el-button>
            <el-button
              v-waves
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >
              {{ $t("table.search") }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div> -->
    <el-button
      type="success"
      class="marginBm"
      @click="handleAdd"
    >添加分类</el-button>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column label="分类名称" prop="name" align="center" />
      <el-table-column label="商品数量" prop="product_num" align="center" />
      <el-table-column label="分类状态" prop="status" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.status == 1 ? "启用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort_num" align="center" />
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      center
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort_num">
          <el-input-number
            v-model="temp.sort_num"
            :min="1"
            :max="99"
            :controls="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="updateData()">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchCateList,
  fetchLevelList,
  productCateEdit,
  productCateUpdate
} from '@/api/index'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      headers: {
        'access-token': getToken()
      },
      activeName: '1',
      orderName: 'share',
      tableKey: 0,
      levelUserList: null,
      list: null,
      orderList: null,
      total: 0,
      userTotal: 0,
      orderTotal: 0,
      listLoading: false,
      userListQuery: {
        page: 1,
        limit: 10
      },
      listQuery: {
        page: 1,
        limit: 20
      },
      orderListQuery: {
        page: 1,
        limit: 10
      },
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑分类',
        create: '添加分类'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleAdd() {
      this.temp = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleTopSuccess(res, file) {
      this.temp.product_image = res.data.image
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getList() {
      this.listLoading = true
      fetchCateList({ type: 2 }).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getUserList() {
      fetchLevelList({
        ...this.userListQuery,
        id: this.temp.id
      }).then((response) => {
        this.levelUserList = response.data.users
        this.userTotal = response.data.total
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.temp = row
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await productCateUpdate({
            id: row.id,
            type: 2
          })
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.getList()
        })
        .catch((err) => {
          console.error(err)
        })
    },
    updateData() {
      productCateEdit(this.temp).then(() => {
        this.$message({ message: '操作成功', type: 'success' })
        this.dialogFormVisible = false
        this.getList()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.baseLine {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-bottom: 22px;
}
.filter-container {
  border-bottom: 1px solid #ccc;
  margin-bottom: 20px;
}
.marginBm {
  margin-bottom: 20px;
}
.dataBox {
  padding: 20px 0;
  border-top: 1px solid #333;
  display: flex;
  .item {
    flex: 1;
  }
}
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
